//index.js
//获取应用实例
const app = getApp();
var util = require('../../utils/util.js');
var _this;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userArea: app.globalData.Maintenance.userArea,
    userInfo: app.globalData.xieYouUserInfo,
    userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
    brandLogo: null,
    brandModelName: '',
    preventReClick: false,
    initOderId:'',
    wxUserInfo: '',
    mePop: false ,// 个人中心
    getUserInfoPop: false,
    buttonClicked: false,
    popConnectionB: false,
    // 2018-9-18
    region: ['请选择', '请选择','请选择'],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this;
    _this.checkSessionFun();
    app.reverseGeocoder(function(){
      var address = app.globalData.Maintenance.userArea;
      _this.setData({
        userArea: app.globalData.Maintenance.userArea,
        region: [address.province, address.city, address.district]
      })
    })
  },
  checkSessionFun:function(){
    const data = wx.getStorageSync('logs');
    const logs = data && data.logs ? data.logs : [];
    wx.setStorageSync('logs', logs);
    wx.checkSession({
      success: function (res) {
        //session 未过期，并且在本生命周期一直有效
        //检查是否有userInfo
        app.judgeGetUserInfo(function (code) {
          // app初始化绑定机型 userBrandModel
          _this.initUserBrandModelFun(code);
          _this.ifOder(code);
          _this.setData({
            userInfo: app.globalData.xieYouUserInfo,
            userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel
          })
          var userArea = _this.userArea;
          _this.popConnectionOpen();
        });
        wx.hideLoading();
      },
      fail: function () {
        //登录态过期
        app.judgeGetUserInfo(function (code) {
          // app初始化绑定机型 userBrandModel
          _this.initUserBrandModelFun(code);
          _this.ifOder(code);
          _this.setData({
            userInfo: app.globalData.xieYouUserInfo,
            userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel
          })
          _this.popConnectionOpen();
        });
        wx.hideLoading();
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '加载中',
    })
    if (app.globalData.xieYouUserInfo.code){
      wx.showNavigationBarLoading() //在标题栏中显示加载
      
      var code = app.globalData.xieYouUserInfo.code
      _this.initUserBrandModelFun(code);
      _this.ifOder(code);
      _this.setData({
        userInfo: app.globalData.xieYouUserInfo,
        userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
        userArea: app.globalData.Maintenance.userArea,
      })
      setTimeout(function () {
        // complete
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
        wx.hideLoading();
      }, 500);
    }else{
      _this.checkSessionFun();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: '一键约保养，保养更快捷',
      path: '/pages/index/index',
      //imageUrl: '/dist/images/no-modle.png',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  // 修改绑定机型数据
  initUserBrandModelFun(code) {
    
    if (typeof code == 'string'){
      var userCode = code
    }else{
      var userCode = code.code
    }
    app.globalData.xieYouUserInfoRoot.userBrandsModel = [];
    app.initUserBrandModel(userCode, function (data) {
      console.log('app初始化绑定机型');
      for (var i = 0; i < data.length; i++) {
        //将用户机型数据存入到全局数组
        app.globalData.xieYouUserInfoRoot.userBrandsModel.push(data[i]);
        // 将选中的机型显示到选择框中
        if (data[i].selected == 1) {
          console.log(data[i]);
          app.globalData.xieYouUserInfoRoot.userBrandModel = data[i]
        }
      }
      if (app.globalData.xieYouUserInfoRoot.userBrandModel == '' || app.globalData.xieYouUserInfoRoot.userBrandModel == null){
        _this.setData({
          userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
          brandLogo: '',
          brandModelName: ''
        })
      }else{
        _this.setData({
          userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
          brandLogo: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.brandLogo,
          brandModelName: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.name
        })
      }
      
    });
  },
  userModel(){
    
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        title: "goback",
        url: '/pages/index/user-model/user-model?goBack=index'
      })
    }
  },
  // 维修保养
  Maintenance(e){
    
    // 判断是否获取地址权限
    if (!app.globalData.Maintenance.userArea || !app.globalData.Maintenance.userArea.latitude){
      // 获取地址权限后才能拿到 latitude
      //打开选择地址  
      app.GetAddressPermissions(true, function (res) {
        if (res) {
          _this.MaintenanceArea(e);
        } else {
          util.alertMsg('提示', '没有获取您的地址权限无法下单', function () {
            return;
          }, function () {
            console.log('用户点击取消');
            return;
          });
        }
      });
    }else{
      _this.MaintenanceArea(e);
    }
   
  },
  MaintenanceArea(e){
    
    _this.setData({
      userArea: app.globalData.Maintenance.userArea
    })
    wx.showLoading({
      title: '加载中',
    })
    _this.initOder();
    // 判断是否有机型
    if (!_this.data.userBrandModel) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择您的机型', function () {
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.navigateTo({
            title: "goback",
            url: '/pages/index/user-model/user-model?goBack=index'
          })
        }
      }, function () {
        console.log('用户点击取消')
      });
      //P.alertMsg('警告', '请选择您的机型');
      return;
    }
    // 获取机型编码
    app.globalData.Maintenance.serviceType = e.currentTarget.dataset.serviceType;
    var serviceType = app.globalData.Maintenance.serviceType;
    // 获取维修类型
    switch (serviceType) {
      case '2':
        app.globalData.Maintenance.serviceTitle = '保养服务';
        break;
      case '1':
        app.globalData.Maintenance.serviceTitle = '保养服务';
        break;
      case '3':
        app.globalData.Maintenance.serviceTitle = '换件服务';
        break;
      case '0':
        app.globalData.Maintenance.serviceTitle = '维修服务';
        break;
    }
    //修改preventReClick值
    _this.setData({
      preventReClick: true,
    })
    if (_this.data.preventReClick) {
      // 服务类型下单
      _this.serviceOrder(serviceType);
    }
  },
  MaintenancePhone(e){
    console.log('e.detail.errMsg=',e.detail.errMsg)
    console.log('e.detail.iv=',e.detail.iv)
    console.log('e.detail.encryptedData=', e.detail.encryptedData)
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      console.log('失败')
      // util.alertMsg('提示', '未授权', function () {
      //   return;
      // }, function () {
      //   return;
      // });
    } else {
      // 判断是否有电话信息
      console.log('成功')
      console.log(app.globalData.xieYouUserInfo);
      // 没有去获取电话信息
      var encryptedData = e.detail.encryptedData,
        iv = e.detail.iv,
        unionId = app.globalData.xieYouUserInfo.unionid;
      console.log('xieyouInfo=', app.globalData.xieYouUserInfo)
      app.getUserPhone(encryptedData, unionId, iv, function (rs) {
        _this.setData({
          userInfo: app.globalData.xieYouUserInfo
        })
        _this.Maintenance(e);
      })
    }
    
  },
  // 订单信息校验
  initOder(callback){
    
    wx.showLoading({
      title: '加载中',
    })
    //判断是否有用户信息&&选择model
    if (_this.data.userBrandModel) {
      app.globalData.Maintenance.brandModelId = _this.data.userBrandModel.brandModel.id;
      var userCode = _this.data.userBrandModel.userCode;
      //var userCode = app.globalData.xieYouUserInfo.code
      //P.sloading('正在查询是否有订单');
      // app.getRepairmanReparing(userCode, function (res) {
      //   console.log('订单信息',res);
      //   // 取消加载中
      //   wx.hideLoading();
      //   if (res.length > 0) {
      //     callback(res);
      //   } else {
      //     callback(res);
      //   }
      // });
    }else{
      // 取消加载中
      wx.hideLoading();
      //有订单不能接单 你下面已经有单了
      // util.alertMsg('提示', '请选择您的机型', function () {
      //   console.log('用户点击确定')
      //   wx.navigateTo({
      //     title: "goback",
      //     url: 'user-model/user-model'
      //   })
      // }, function () {
      //   console.log('用户点击取消')
      // });
      // 没有用户信息
      console.log('没有用户信息')
    }
  },
  // 判断是否有订单 现在可以下多个订单
  ifOder: function (code){
    
    if (typeof code == 'string') {
      var userCode = code
    } else {
      var userCode = code.code
    }
    var queryUserCompleteParam = {
      userCode: userCode,
      search: null,
      page: 1,
      limit: 20,
      orderStatus: '10,20,30,40'
    }
    app.getUserOrderList(queryUserCompleteParam, function (res) {
      console.log('订单信息', res);
      res = res.data.results
      if (res.length > 0) {
        _this.setData({
          initOderId: res,
        })
      }else{
        _this.setData({
          initOderId: '',
        })
      }
    });
    
  },
  // 做保养/维修
  serviceOrder(serviceType){
    // 取消加载中
    wx.hideLoading();
    // 判断是否有地址
    if (_this.data.userArea) {
      // 地址、机型、维修类型
      // 进入信息页
        // if (!_this.data.buttonClicked) {
        //   util.buttonClicked(_this);
        //   wx.navigateTo({
        //     title: "goback",
        //     url: '/pages/little-service-massage/little-service-massage'
        //   })
        // }
      // 进入械友推荐商品
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateTo({
          title: "goback",
          url: '/pages/recommend-products-list/recommend-products-list'
        })
      }
    } else {
      // 选择地址弹窗
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('提示', '请选择您的地址', function () {
      }, function () {
        console.log('用户点击取消')
      });
      //修改preventReClick值
      _this.setData({
        preventReClick: false,
      })
      return false;
    }
  },
  // 选择地区
  chooseArea(){
    
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        title: "goback",
        url: '/pages/index/choose-area/choose-area'
      })
    }
  },
  // 我的订单
  myOder(){
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/service-list/service-list'
      })
    }
    setTimeout(function () {
      _this.mePopClose()
    }, 500);
  },
  // 正在进行的的订单
  goToOder(){
    
    var initOderId = this.data.initOderId
    if (initOderId.length > 1){
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateTo({
          url: '/pages/service-list/service-list'
        })
      }
    } else if (initOderId.length = 1){
      if (!_this.data.buttonClicked) {
        util.buttonClicked(_this);
        wx.navigateTo({
          url: '/pages/service-detail/service-detail?id=' + initOderId[0].id + '&type=ing'
        })
      }
    }
  },
  // 下载械友APP
  xieyouApp(){
    wx.navigateTo({
      url: '../recommend-products-list/recommend-products-list',
    })
    // wx.openUrl({
    //   url: 'http://a.app.qq.com/o/simple.jsp?pkgname=com.ulpey.xieyou',
    //   success: function(res) {
    //     console.log(res);
    //   },
    //   fail: function(res) {
    //     console.log(res);
    //   },
    //   complete: function(res) {
    //     console.log(res);
    //   },
    // })
    
    // if (!_this.data.buttonClicked) {
    //   util.buttonClicked(_this);
    //   wx.navigateTo({
    //     url: '/pages/open-html/open-html',
    //     success: function(res) {},
    //     fail: function(res) {},
    //     complete: function(res) {},
    //   })
    // }
  },
  // 打开个人中心
  mePopOpen: function (e) {
    _this.getUserDevice();
    var wxUserInfo = _this.data.wxUserInfo;
    if ( !wxUserInfo || !wxUserInfo.avatarUrl){
      app.wxGetUserInfo(function(res){
        _this.setData({
          wxUserInfo: res.userInfo,
          mePop: true
        })
      })
    }else{
      _this.setData({
        mePop: true
      })
    }
  },
  // 关闭个人中心
  mePopClose:function(){
    this.setData({
      mePop: false
    })
  },
  // 成为维修师
  becomeMechanic:function(){
    app.accountAll(_this.data.userInfo.code, function(res){
      if (res == null){
        // status 1 成功 2 失败 0 审核中
        _this.setData({
          mePop: false
        })
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.navigateTo({
            url: '/pages/become-mechanic/become-mechanic'
          })
        }
        setTimeout(function () {
          _this.mePopClose()
        }, 500);
      } else if (res.status == 0){
        util.alertMsg('提示', '维修师认证资料审核中,请耐心等待', function () {
          return;
        }, function () {
          console.log('用户点击取消');
          return;
        });
      } else if (res.status == 2) {
        util.alertMsg('提示', '审核失败，是否重新申请', function () {
          if (!_this.data.buttonClicked) {
            util.buttonClicked(_this);
            wx.navigateTo({
              url: '/pages/become-mechanic/become-mechanic'
            })
          }
          setTimeout(function () {
            _this.mePopClose()
          }, 500);
          return;
        }, function () {
          console.log('用户点击取消');
          return;
        });
      } else if (res.status == 1) {
        util.alertMsg('提示', '您已经是维修师，去下载械友App赚钱吧~', function () {
          _this.xieyouApp();
          setTimeout(function () {
            _this.mePopClose()
          }, 500);
          return;
        }, function () {
          console.log('用户点击取消');
          return;
        });
      } 
    })
  },
  becomeMyFund:function(){
    
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/my-fund/my-fund'
      });
    }
    
    setTimeout(function(){
      _this.mePopClose()
    },500);
  },
  getUserInfoFun:function(){
    
    _this.setData({
      getUserInfoPop: false
    })
    //登录态过期
    app.judgeGetUserInfo(function (code) {
      // app初始化绑定机型 userBrandModel
      _this.initUserBrandModelFun(code);
      _this.ifOder(code);
      _this.setData({
        userInfo: app.globalData.xieYouUserInfo,
        userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
        userArea: app.globalData.Maintenance.userArea,
      })
    });
  },
  // 我的优惠券
  myCoupon:function(){
    
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/my-coupon/my-coupon'
      });
    }
    setTimeout(function () {
      _this.mePopClose()
    }, 500);
  },
  // 测人脉活动
  closePopConnection:function(){
    
     _this.setData({
       popConnectionB: false
     })
  },
  // 判断地区打开侧人脉活动
  popConnectionOpen: function () {
    
    var userArea = _this.data.userArea;
    if (userArea.province == '山东省') {
      _this.setData({
        popConnectionB: true
      })
      // setTimeout(function(){
      //   _this.setData({
      //     popConnectionB: false
      //   })
      // },3000)
    }
  },
  // 人脉H5
  goToConUrl:function(){
    
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/activity/connection/connection?userCode=' + _this.data.userInfo.code
      });
    }
  },
  /**
   * 2018-9-18
   */
  // 地址
  bindRegionChange: function (e) {
    _this.setData({
      region: e.detail.value
    })
    // 获取所有省
    if (app.globalData.allArea) {
      _this.setData({
        provinceList: app.globalData.allArea.result[0],
        cityList: app.globalData.allArea.result[1],
        districtList: app.globalData.allArea.result[2]
      })
      _this.getAdcode();
      // 取消加载中
      wx.hideLoading();
    } else {
      qqmapsdk.getCityList({
        success: function (res) {
          _this.setData({
            provinceList: res.result[0],
            cityList: res.result[1],
            districtList: res.result[2],
          })
          // 取消加载中
          wx.hideLoading();
          app.globalData.allArea = res;
          _this.getAdcode();
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function (res) {
          console.log(res);
        }
      });
      // 根据城市，获取他下面的所有城市和区县
    }
  },
  getAdcode:function(){
    var provinceList = _this.data.provinceList,
      cityList = _this.data.cityList,
      districtList = _this.data.districtList,
      region = _this.data.region;
    for (var i = 0; i < provinceList.length; i++){
      if (provinceList[i].fullname == region[0]){
        var proBef = provinceList[i].id.match(/^.{0,2}/)[0];
        // 以proBef 开头
        proBef = new RegExp("^" + proBef);
        // 去allProvinceCity找city
        for (var a = 0; a < cityList.length; a++) {
          if (cityList[a].id.search(proBef) != '-1') {
            // 判断是否是直辖市 判断是否由两个零结尾
            if (cityList[a].id.search(/00$/g) == '-1' && cityList[a].fullname == region[2]) {
              app.globalData.Maintenance.userArea.adcode = cityList[a].id;
              app.globalData.Maintenance.userArea.latitude = cityList[a].location.lat;
              app.globalData.Maintenance.userArea.longitude = cityList[a].location.lng;
              app.globalData.Maintenance.userArea.province = region[0];
              app.globalData.Maintenance.userArea.city = region[1];
              app.globalData.Maintenance.userArea.district = region[2];
              app.globalData.Maintenance.userArea.formattedAddresses = '';
              return;
            } else if (cityList[a].id.search(/00$/g) != '-1' && cityList[a].fullname == region[1]){
              // 获得前4位代
              var cityBef = cityList[a].id.match(/^.{0,4}/)[0];
              for (var b = 0; b < districtList.length; b++) {
                if (districtList[b].id.search(cityBef) != '-1' && districtList[b].fullname == region[2]) {
                  app.globalData.Maintenance.userArea.adcode = districtList[b].id;
                  app.globalData.Maintenance.userArea.latitude = districtList[b].location.lat;
                  app.globalData.Maintenance.userArea.longitude = districtList[b].location.lng;
                  app.globalData.Maintenance.userArea.province = region[0];
                  app.globalData.Maintenance.userArea.city = region[1];
                  app.globalData.Maintenance.userArea.district = region[2];
                  app.globalData.Maintenance.userArea.formattedAddresses = '';
                  return;
                }
              }
            }
            
            // return districtList[b].id;
          }
          
          
        }
      }
    }
  },
  goBecomeMaster:function(e){
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      console.log('失败')
    } else {
      // 判断是否有电话信息
      // 没有去获取电话信息
      var encryptedData = e.detail.encryptedData,
        iv = e.detail.iv,
        unionId = app.globalData.xieYouUserInfo.unionid;
      console.log('xieyouInfo=', app.globalData.xieYouUserInfo)
      app.getUserPhone(encryptedData, unionId, iv, function (rs) {
        _this.setData({
          userInfo: app.globalData.xieYouUserInfo
        })
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.navigateTo({
            url: '/pages/become-master/become-master'
          });
        }
      })
    }
  },
  // 查询是否有设备
  getUserDevice: function () {
    let data = {};
    wx.showLoading({
      title: '正在加载...',
    })
    if (!_this.data.userInfo){
      _this.setData({
        userInfo: app.globalData.xieYouUserInfo
      })
    }
    
    data.userCode = _this.data.userInfo.code;
    // 签到日期
    app.getMassage(data, null, 'getUserDevice', function (res) {
      wx.hideLoading();
      let date = res.data;
      if (res.data) {
        _this.setData({
          masterList: res.data
        })
        //util.alertMsg('添加成功', 'success');
      }
    }, 'GET')
  },
  // 去**页
  goNavTo: function (e) {
    app.goNavTo(e, _this.data.buttonClicked, _this);
  },
  // 返回上一页
  goBack: function (e) {
    app.goBack(e, _this.data.buttonClicked, _this);
  },
  /*
  * 2018-11-5
  */
  // 联系客服
  customerServiceTell: function () {
    app.customerServiceTell();
  },
  goToWxs:function(){
    wx.navigateToMiniProgram({
      appId:'wxbec0f7cb81f52be1',
      path:'pages/index/index',
      extraData: {
      },
      envVersion: 'develop',
      success(res) {
        // 打开成功
      }
    })
  },
})

